package com.kaguya.vams.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kaguya.vams.common.constant.Constants;
import com.kaguya.vams.domain.AccessUser;
import com.kaguya.vams.domain.entity.SysUser;
import com.kaguya.vams.service.impl.SysUserServiceImpl;
import com.kaguya.vams.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登录处理
 * @author : kaguya
 * @date : 19:03 2021/8/1
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserServiceImpl sysUserService; //用户业务层

    @Autowired
    private RedisUtils redisUtils; //redis缓存工具类

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("UserDetailsService - loadUserByUsername");
        //从数据库中查询用户，并返回UserDetails
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        SysUser sysUser = sysUserService.getOne(wrapper);

        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名或密码不正确!");
        }

        return new AccessUser(sysUser.getUsername(),sysUser.getPassword(),this.getUserAuthorities(sysUser.getId()));
    }

    /**
     * 获取用户权限集合
     * @return
     */
    public List<GrantedAuthority> getUserAuthorities(Long userId){

        log.info("根据用户id获取权限集合");

        //优先从缓存中获取，如果缓存中没有，调用方法从数据库获取
        String auths = sysUserService.getUserAuthorities(userId);

        return AuthorityUtils.commaSeparatedStringToAuthorityList(auths);
    }
}
